
import nw from "nw-lafjs";
import {ok} from "@/utils/responseUtil";

// @ts-ignore
export default async function (ctx: FunctionContext) {
  //1.查询全部菜单
  let allPermissions = await nw.db.findListByWhereJson({
    dbName:"permission",
    whereJson:{deleted:0}
  })
  if (nw.util.isNull(allPermissions)||allPermissions.length===0){
    return ok([])
  }
  //2.循环构建菜单
  let treeMap = new Map()
  for (let i = 0; i < allPermissions.length; i++) {
    let permission = allPermissions[i]
    permission.children = []
    if (treeMap.has(permission.pid)){
      treeMap.get(permission.pid).push(permission)
    }else {
      let array = [permission]
      treeMap.set(permission.pid,array)
    }
  }

  for (let [_, value] of treeMap) {
    for (let i = 0; i < value.length; i++) {
      let each = value[i]
      if (treeMap.has(each._id)){
        each.children = treeMap.get(each._id)
      }
    }
  }


  console.log("菜单树===")
  console.log(JSON.stringify(treeMap))
  return ok(treeMap.get("0"))

}
